package com.tianjishuju.cimiss.station.station.api;

import com.tianjishuju.cimiss.station.station.model.RealHost;
import com.tianjishuju.cimiss.station.station.model.VMHost;
import com.tianjishuju.cimiss.station.station.util.ConvertUtil;
import com.tianjishuju.cimiss.station.station.util.HttpUtil;
import com.tianjishuju.cimiss.station.station.util.TrustAnyTrustManager;
import com.tianjishuju.cimiss.station.station.util.SignatureUtils;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;

@RestController
@RequestMapping("/useVmHostAPI")
public class NoUseAPI {
    private static Logger logger = Logger.getLogger(NoUseAPI.class);

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    private SimpleDateFormat yyyyMMddHH = new SimpleDateFormat("yyyyMMddHH");

    @Value ("${cimissUrl:http://10.230.89.55/cimiss-web/api?userId=BECQ_XXZX_show&pwd=yxjkk}")
    private String cimissUrl="http://10.230.89.55/cimiss-web/api?userId=BECQ_XXZX_show&pwd=yxjkk";

    @Value("${find.host.vmhosts:http://10.230.126.249:8080}")
    private String hosts = "http://10.230.126.249:8080";

    @Value("${AccessKeySecret:2a860b8a0f57419f}")
    private String AccessKeySecret = "2a860b8a0f57419f";

    @Value("${find.host.OceanStor9000:https://10.230.123.101:8088}")
    private String OceanStor9000 = "https://10.230.123.101:8088";

    @Value("${find.businessCardListUserName.userName:admin}")
    private String userName = "admin";

    @Value("${find.businessCardListUserName.password:admin}")
    private String password = "admin";

    //10.230.126.249:8080
    @Value("${find.healhost.host:10.230.126.249:8080}")
    private String healhost = "10.230.126.249:8080";
    private String sessionId = loginTo();
    private long start;//sessionId建立时间

    private List<RealHost> realHostList ;//物理机列表
    private List<RealHost> realHostCloudList ;//物理机列表
    private List<VMHost> vmHostList;//虚拟机列表
    private List<VMHost> vmHostCloudList;//虚拟机列表
    private Map<String, Object> cloud = null;//气象云



    /**
     * 登陆返回 sessionId
     *
     * @return sessionId
     */
    public static void main(String[] args) throws Exception{
//        SSLContext sc = SSLContextUtil.createSslContext();
//        SSLContextUtil.post("https://172.24.186.114:8443/imcrs/absm/businessCardList","123");

//        Map<String,String> mapPar = new HashMap<>();
//        mapPar.put("userName","admin");
//        mapPar.put("passWord","admin");
//        Map<String, Object> map = HttpUtil.doGet("http://172.24.186.114:8443/imcrs/absm/businessCardList", mapPar);

        Map<String, Object> map = HttpUtil.doGet("https://172.24.186.114:8443/imcrs/absm/businessCardList", new HashMap());

        Map httpRtnBodyToMap = getHttpRtnBodyToMap(map);

        String sessionId = null;
        try {
            sessionId = (String) httpRtnBodyToMap.get("sessionId");
        } catch (Exception e) {
            logger.error ("无法获取sessionId,请检查网络连接");
        }
        System.out.println("------sessionId---------"+sessionId);
    }

    public String loginTo() {
        Map<String, Object> map = HttpUtil.doPost("http://10.230.126.249:8080/cas/spring_check?encrypt=true&lang=cn&name=WpIxDAPVsRM%3D&password=WpIxDAPVsRM%3D", new HashMap());
        Map httpRtnBodyToMap = getHttpRtnBodyToMap(map);

        String sessionId = null;
        try {
            sessionId = (String) httpRtnBodyToMap.get("sessionId");
        } catch (Exception e) {
            logger.error ("无法获取sessionId,请检查网络连接");
            return null;
        }
        start = new Date().getTime();
        return sessionId;
    }

    /**弃用改用excel
     * 气象云----这是计算出来的
     * @return
     */
    @GetMapping("/getCloud")
    public Map<String, Object> getCloud(){
        long time = new Date().getTime();
        if (((time - start) / 1000) < 1800) {
            if (cloud!=null){
                return cloud;
            }
        }
        sessionId = loginTo();
        Map<String, Object> rtn = new HashMap<>();
        rtn.put("RealHostCount",getAllRealHosts());
        rtn.put("VMHostCount",getVMHosts());
        long CPUcount=0;
        long memorySize=0;
        long diskSize=0;
        for (RealHost realHost : realHostList) {
            long integer = Long.valueOf(realHost.getCpuCount());
            long aLong = Long.valueOf(realHost.getMemorySize());
            long disk = Long.valueOf(realHost.getDiskSize());
            CPUcount=CPUcount+integer;
            memorySize = memorySize +aLong;
            diskSize = diskSize +disk;
        }
        rtn.put("CPUcount",CPUcount);
        rtn.put("memorySize",memorySize);
        rtn.put("diskSize",diskSize);
        cloud=rtn;
        System.out.println(rtn);
        return rtn;
    }

    /**
     *
     * @return
     */
    /**
     * 风险服务器top5
     * @return
     */
    @RequestMapping("/getRiskService")
    public List<RealHost> getRiskService(){
        List<RealHost> relustList=new ArrayList<>();

        RealHost realHost1 = new RealHost();
        realHost1.setIp("172.24.176.151");
        realHost1.setFallLevel(3);
        realHost1.setSafetyGrade("永恒之恋");

        relustList.add(realHost1);

        RealHost realHost2 = new RealHost();
        realHost2.setIp("172.24.186.220");
        realHost2.setFallLevel(3);
        realHost2.setSafetyGrade("永恒之恋 虚拟货币挖坑 威胁情报");

        relustList.add(realHost2);

        RealHost realHost3 = new RealHost();
        realHost3.setIp("10.230.64.21");
        realHost3.setGroupName("计财处");
        realHost3.setFallLevel(3);
        realHost3.setSafetyGrade("永恒之恋 SMB扫描 IP扫描");

        relustList.add(realHost3);

        RealHost realHost4 = new RealHost();
        realHost4.setIp("10.230.58.19");
        realHost4.setFallLevel(3);
        realHost4.setSafetyGrade("永恒之恋");

        relustList.add(realHost4);

        RealHost realHost5 = new RealHost();
        realHost5.setIp("10.230.58.15");
        realHost5.setFallLevel(3);
        realHost1.setSafetyGrade("永恒之恋 高危弱密码");

        relustList.add(realHost4);
        return relustList;
    }
    /**
     * 主机连接数 top5
     * @return
     */
    @RequestMapping("/getService")
    public List<Map<String,Object>> getService(){
        List<Map<String,Object>> relustList=new ArrayList<>();

        Map<String,Object> map1 = new HashMap<>();
        map1.put("serviceName","host1");
        map1.put("system","旅游");
        map1.put("num",534);

        relustList.add(map1);

        Map<String,Object> map2 = new HashMap<>();
        map2.put("serviceName","host2");
        map2.put("system","交通");
        map2.put("num",496);


        relustList.add(map2);

        Map<String,Object> map3 = new HashMap<>();
        map3.put("serviceName","host3");
        map3.put("system","水利");
        map3.put("num",407);


        relustList.add(map3);

        Map<String,Object> map4 = new HashMap<>();
        map4.put("serviceName","host4");
        map4.put("system","农业");
        map4.put("num",371);


        relustList.add(map4);

        Map<String,Object> map5 = new HashMap<>();
        map5.put("serviceName","host5");
        map5.put("system","国土");
        map5.put("num",298);


        relustList.add(map5);

        return relustList;
    }
    /*
     */
    @GetMapping("/getRiskServiceData")
    public  List<RealHost> getRiskServiceData() {
//        getAllRealHosts();
//        System.out.println(realHostList.size());
//        realHostCloudList = new ArrayList<>();
//        String cookie = "JSESSIONID=" + sessionId + "; path=/cas/; domain=10.230.126.249; HttpOnly; Expires=Tue, 19 Jan 2038 03:14:07 GMT;";
//        URL url = null;
//        String monitorStr = null;
//        monitorStr = "http://10.230.126.249:8080/cas/casrs/host/id/%s";

        realHostCloudList = new ArrayList<>();
        for (int i = 0; i < 5 ; i++) {
            RealHost realHost = new RealHost();
            if(i == 0){
                realHost.setIp("172.24.176.151");
                realHost.setFallLevel(3);
            }else if(i == 1){
                realHost.setIp("172.24.186.220");
                realHost.setFallLevel(3);
            }else if(i == 2){
                realHost.setIp("10.230.64.21");
                realHost.setGroupName("计财处");
                realHost.setFallLevel(3);
            }else if(i == 3){
                realHost.setIp("10.230.58.19");
                realHost.setFallLevel(3);
            }else if(i == 4){
                realHost.setIp("10.230.58.15");
                realHost.setFallLevel(3);
            }
        }
        return realHostCloudList;
    }

    @GetMapping("/getHostStatus")
    public synchronized List<RealHost> getHostData() {
        getAllRealHosts();
        System.out.println(realHostList.size());
        realHostCloudList = new ArrayList<>();
        String cookie = "JSESSIONID=" + sessionId + "; path=/cas/; domain=10.230.126.249; HttpOnly; Expires=Tue, 19 Jan 2038 03:14:07 GMT;";
        URL url = null;
        String monitorStr = null;
        monitorStr = "http://10.230.126.249:8080/cas/casrs/host/id/%s";

        ////////////////
        int maxThreadNum = (int) Math.ceil(realHostList.size()/5d) ;
        CountDownLatch startGate = new CountDownLatch(1);
        CountDownLatch endGate = new CountDownLatch(maxThreadNum);

        int splitNum = (int) Math.ceil(realHostList.size()*1.0/maxThreadNum);

        for(int i=0;i<maxThreadNum;i++){
            final int splitIndex = i;
            Runnable runnable = new RealProgress(cookie,monitorStr,splitIndex,splitNum,realHostList, realHostCloudList,startGate,endGate);
//            new Thread((runnable) -> {
//                try {
//                    Thread.sleep(2 * 60 * 60 * 1000);
//
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }).start();
            try {
                Thread thread = new Thread(runnable);
//                thread.sleep(1000 );
                thread.start();
            }catch (Exception e) {
                    e.printStackTrace();
            }

//            new Thread(runnable).start();
        }
        try {
            startGate.countDown();
            endGate.await();
        } catch (Exception e2) {
            logger.error(" CountDownLatch error -------", e2);
        }
        ///////////////

//        for(RealHost realHost:realHostList){
//            String id = realHost.getId();
//            String monitorUrl = String.format(monitorStr, id);
//            try {
//                url = new URL(monitorUrl);
//                URLConnection conn = url.openConnection();
//                conn.setRequestProperty("Cookie", cookie);
//                conn.setDoInput(true);
//                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//                StringBuilder sb = new StringBuilder();
//                String line = null;
//                while ((line = br.readLine()) != null) {
//                    sb.append(line);
//                }
//                Document doc = DocumentHelper.parseText(sb.toString());
//                Element rootElement = doc.getRootElement();
//                Iterator iterator = rootElement.elementIterator();
//                RealHost couldRealHost = new RealHost();
//                couldRealHost.setId(realHost.getId());
//                couldRealHost.setName(realHost.getName());
//                while (iterator.hasNext()) {
//                    Element next = (Element) iterator.next();
//                    String name= next.getName();
//                    if("status".equals(name)) couldRealHost.setHostStatus(next.getStringValue());
//                }
//                realHostCloudList.add(couldRealHost);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        return realHostCloudList;
    }

    @GetMapping("/getVmData")
    public synchronized List<VMHost> getVmData() {
        getAllRealHosts();
        System.out.println(realHostList.size());
        vmHostCloudList = new ArrayList<>();
        String cookie = "JSESSIONID=" + sessionId + "; path=/cas/; domain=10.230.126.249; HttpOnly; Expires=Tue, 19 Jan 2038 03:14:07 GMT;";
        URL url = null;
        String monitorStr = null;
        monitorStr = "http://10.230.126.249:8080/cas/casrs/vm/vmList?hostId=%s";

        ////////////////
        System.out.println(realHostList.size()/5d);
        int maxThreadNum = (int) Math.ceil(realHostList.size()/5d) ;
//        maxThreadNum = 12;
        CountDownLatch startGate = new CountDownLatch(1);
        CountDownLatch endGate = new CountDownLatch(maxThreadNum);

        int splitNum = (int) Math.ceil(realHostList.size()*1.0/maxThreadNum);

        for(int i=0;i<maxThreadNum;i++){
            final int splitIndex = i;
            Runnable runnable = new VmProgress(cookie,monitorStr,splitIndex,splitNum,realHostList, vmHostCloudList,startGate,endGate);
            new Thread(runnable).start();
        }
        try {
            startGate.countDown();
            endGate.await();
        } catch (Exception e2) {
            logger.error(" CountDownLatch error -------", e2);
        }

        /////////////////////
//        for(RealHost realHost:realHostList){
//            VMHost couldVmHost = new VMHost();
//            couldVmHost.setId(realHost.getId());
//            couldVmHost.setName(realHost.getName());
//            double cpu = 0;
//            double men = 0;
//            String id = realHost.getId();
//            String vmUrl = String.format(vmStr, id);
//            try {
//                url = new URL(vmUrl);
//                URLConnection conn = url.openConnection();
//                conn.setRequestProperty("Cookie", cookie);
//                conn.setDoInput(true);
//                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//                StringBuilder sb = new StringBuilder();
//                String line = null;
//                while ((line = br.readLine()) != null) {
//                    sb.append(line);
//                }
//                Document doc = DocumentHelper.parseText(sb.toString());
//                Element rootElement = doc.getRootElement();
//                Iterator iterator = rootElement.elementIterator();
//                while (iterator.hasNext()) {
//                    Element next = (Element) iterator.next();
//                    Iterator iterator1 = next.elementIterator();
//                    while (iterator1.hasNext()) {
//                        Element next1 = (Element) iterator1.next();
//                        String name= next1.getName();
//                        if("cpuRate".equals(name)) cpu = cpu + Double.parseDouble(next1.getStringValue());
//                        if("memRate".equals(name)) men = men + Double.parseDouble(next1.getStringValue());
////                        if("status".equals(name)) couldVmHost//vm 状态
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            couldVmHost.setVmCupRate(cpu);
//            couldVmHost.setVmMemRate(men);
//            vmHostCloudList.add(couldVmHost);
//        }
        return vmHostCloudList;
    }

    @GetMapping("/getRealData")
    public synchronized List<RealHost> getRealData() {
        getAllRealHosts();
//        System.out.println(realHostList.size());
        realHostCloudList = new ArrayList<>();
        String cookie = "JSESSIONID=" + sessionId + "; path=/cas/; domain=10.230.126.249; HttpOnly; Expires=Tue, 19 Jan 2038 03:14:07 GMT;";
        String monitorStr = "http://10.230.126.249:8080/cas/casrs/host/id/%s/monitor";
        ////////////////
//        System.out.println(realHostList.size()/5d);
        int maxThreadNum = (int) Math.ceil(realHostList.size()/5d);
        CountDownLatch startGate = new CountDownLatch(1);
        CountDownLatch endGate = new CountDownLatch(maxThreadNum);

        int splitNum = (int) Math.ceil(realHostList.size()*1.0/maxThreadNum);
        for(int i=0;i<maxThreadNum;i++){
            final int splitIndex = i;
            Runnable runnable = new RealProgress(cookie,monitorStr,splitIndex,splitNum,realHostList, realHostCloudList,startGate,endGate);
            new Thread(runnable).start();
        }
        try {
            startGate.countDown();
            endGate.await();
        } catch (Exception e2) {
            logger.error(" CountDownLatch error -------", e2);
        }
        ///////////////
//        URL url = null;
//        String monitorStr = null;
//        monitorStr = "http://10.230.126.249:8080/cas/casrs/host/id/%s/monitor";
//        for(RealHost realHost:realHostList){
//            String id = realHost.getId();
//            String monitorUrl = String.format(monitorStr, id);
//            try {
//                url = new URL(monitorUrl);
//                URLConnection conn = url.openConnection();
//                conn.setRequestProperty("Cookie", cookie);
//                conn.setDoInput(true);
//                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//                StringBuilder sb = new StringBuilder();
//                String line = null;
//                while ((line = br.readLine()) != null) {
//                    sb.append(line);
//                }
//                Document doc = DocumentHelper.parseText(sb.toString());
//                Element rootElement = doc.getRootElement();
//                Iterator iterator = rootElement.elementIterator();
//                RealHost couldRealHost = new RealHost();
//                couldRealHost.setId(realHost.getId());
//                couldRealHost.setName(realHost.getName());
//                while (iterator.hasNext()) {
//                    Element next = (Element) iterator.next();
//                    String name= next.getName();
//                    if("cpuRate".equals(name)) couldRealHost.setCpuRate(next.getStringValue());
//                    if("memRate".equals(name)) couldRealHost.setMemRate(next.getStringValue());
//                }
//                realHostCloudList.add(couldRealHost);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        System.out.println("---St--- : " + realHostCloudList.size());
        return realHostCloudList;
    }
    /**
     * 1.查询物理主机列表 数量
     */
    @GetMapping("/cas/casrs/host")
    public synchronized List<RealHost> getAllRealHosts() {
        long time = new Date().getTime();
        if (((time - start) / 1000) > 1800) {
            sessionId = loginTo();
        }
        realHostList = new ArrayList<>();
        String urlString = hosts + "/cas/casrs/host";//"http://10.230.126.249:8080/cas/casrs/hostpool/all";
        String cookie = "JSESSIONID=" + sessionId + "; path=/cas/; domain=10.230.126.249; HttpOnly; Expires=Tue, 19 Jan 2038 03:14:07 GMT;";
        URL url = null;
        try {
            url = new URL(urlString);
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("Cookie", cookie);
            conn.setDoInput(true);
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            Document doc = DocumentHelper.parseText(sb.toString());
            Element rootElement = doc.getRootElement();
            Iterator iterator = rootElement.elementIterator();
            while (iterator.hasNext()) {
                Element next = (Element) iterator.next();
                Iterator iterator1 = next.elementIterator();
                RealHost realHost = new RealHost();
                while (iterator1.hasNext()) {
                    Element next1 = (Element) iterator1.next();
                    String name = next1.getName();
                    if ("id".equals(name)) realHost.setId(next1.getStringValue());
                    if ("ip".equals(name)) realHost.setIp(next1.getStringValue());
                    if ("name".equals(name)) realHost.setName(next1.getStringValue());
                    if ("type".equals(name)) realHost.setType(next1.getStringValue());
                }
                realHostList.add(realHost);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(realHostList.size());
        return realHostList;
    }


    /**
     * 2.查询虚拟主机列表
     * 2.1查询主机池列表  返回数量
     */
    @GetMapping("/cas/casrs/hostpool/all")
    public int getVMHosts() {
        long time = new Date().getTime();
        if (((time - start) / 1000) > 1800) {
            sessionId = loginTo();
        }
        vmHostList = new ArrayList<>();
        String urlString = hosts + "/cas/casrs/hostpool/all";//"http://10.230.126.249:8080/cas/casrs/hostpool/all";
        String cookie = "JSESSIONID=" + sessionId + "; path=/cas/; domain=10.230.126.249; HttpOnly; Expires=Tue, 19 Jan 2038 03:14:07 GMT;";
        URL url = null;
        try {
            url = new URL(urlString);
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("Cookie", cookie);
            conn.setDoInput(true);
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println(sb);
            Document doc = DocumentHelper.parseText(sb.toString());
            Element rootElement = doc.getRootElement();
            System.out.println("rootElement>>" + rootElement.getName());
            Iterator iterator = rootElement.elementIterator();
            while (iterator.hasNext()) {
                Element next = (Element) iterator.next();
                System.out.println("next>>" + next.getName());
                Iterator iterator1 = next.elementIterator();
                VMHost realHost = new VMHost();
                while (iterator1.hasNext()) {
                    Element next1 = (Element) iterator1.next();
                    String name = next1.getName();
                    if ("id".equals(name)) realHost.setId(next1.getStringValue());
                    if ("name".equals(name)) realHost.setName(next1.getStringValue());
                    if ("operatorGroupId".equals(name)) realHost.setOperatorGroupId(next1.getStringValue());
                    if ("operatorGroupCode".equals(name)) realHost.setOperatorGroupCode(next1.getStringValue());
                    if ("childNum".equals(name)) realHost.setChildNum(next1.getStringValue());
                }
                vmHostList.add(realHost);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(vmHostList.size());
        return vmHostList.size();

    }

    /**
     * 2.2 查询主机池下所有虚机
     *
     * @param id
     */
    @GetMapping("/cas/casrs/vm/vmList")
    public void getOneHost(@RequestParam("id") String id) {
        Map<String, Object> map = HttpUtil.doGet(hosts + "/cas/casrs/vm/vmList?hpId=" + id);

        Map map1 = getHttpRtnBodyToMap(map);
        System.out.println(map1);
    }

    /**
     * 3.CPU总核数、内存总数
     * 3.1查询所有主机的详细信息
     *
     * @param id
     */

    public void getAllHosts(String id,RealHost realHost) throws Exception{

        String urlString = hosts + "/cas/casrs/host/id/"+id;//"http://10.230.126.249:8080/cas/casrs/hostpool/all";
        String cookie = "JSESSIONID=" + sessionId + "; path=/cas/; domain=10.230.126.249; HttpOnly; Expires=Tue, 19 Jan 2038 03:14:07 GMT;";
        URL url = null;

        url = new URL(urlString);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Cookie", cookie);
        conn.setDoInput(true);
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        Document doc = DocumentHelper.parseText(sb.toString());
        Element rootElement = doc.getRootElement();
        Iterator iterator = rootElement.elementIterator();
        while (iterator.hasNext()) {
            Element next1 = (Element) iterator.next();
            String name = next1.getName();
            makeRealHost(realHost, next1, name);
        }
    }

    public void makeRealHost(RealHost realHost, Element next1, String name) {
        switch (name){
            case "id":{
                realHost.setId(next1.getStringValue());
                break;
            }
            case "name":{
                realHost.setName(next1.getStringValue());
                break;
            }
            case "ip":{
                realHost.setIp(next1.getStringValue());
                break;
            }
            case "vendor":{
                realHost.setVendor(next1.getStringValue());
                break;
            }
            case "cpuCount":{
                realHost.setCpuCount(next1.getStringValue());
                break;
            }
            case "cpuModel":{
                realHost.setCpuModel(next1.getStringValue());
                break;
            }
            case "model":{
                realHost.setModel(next1.getStringValue());
                break;
            }
            case "cpuFrequence":{
                realHost.setCpuFrequence(next1.getStringValue());
                break;
            }
            case "diskSize":{
                realHost.setDiskSize(next1.getStringValue());
                break;
            }
            case "memorySize":{
                realHost.setMemorySize(next1.getStringValue());
                break;
            }
            case "status":{
                realHost.setStatus(next1.getStringValue());
                break;
            }
            case "cpuSockets":{
                realHost.setCpuSockets(next1.getStringValue());
                break;
            }
            case "cpuCores":{
                realHost.setCpuCores(next1.getStringValue());
                break;
            }
        }
    }
    /**4、已分配CPU核数、已分配内存总数
     2中的虚拟主机列表所有的CPU核数、内存总数累加结果为已分配CPU核数、已分配内存总数
     */
    /**
     * 5.共享存储总量、已使用量
     * 5.1 查询cas所有主机池与2.1相同
     * 5.2 查询主机池下共享文件系统列表
     *
     * @param hpId 主机池ID
     */
    @GetMapping("/cas/casrs/hostpool/shareFile/list")
    public void getHostsShareFile(@RequestParam("hpId") String hpId) {
        Map<String, Object> map = HttpUtil.doGet(hosts + "/cas/casrs/hostpool/shareFile/" + hpId);

        System.out.println(map);
    }

    @GetMapping("/getBusinessCardList")
    public List<RealHost> getBusinessCardList() {
        List<RealHost> realHostList = new ArrayList<RealHost>();
        try {
            String host = "172.24.186.114:8443";
            String url = "https://" + host + "/imcrs/absm/businessCardList";
//            String userName = "admin", password = "admin";

            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
            httpClientConnectionManager.setMaxTotal(100);
            httpClientConnectionManager.setDefaultMaxPerRoute(20);

            // ssl context (取消证书认证)
            SSLContext sslcontext = SSLContext.getInstance("SSL");
            httpClientBuilder.setSSLContext(sslcontext);
            sslcontext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());

            //取消验证 hostName
            httpClientBuilder.setSSLHostnameVerifier((hostname, session) -> {
                //强行返回true 即验证成功
                return true;
            });

            CloseableHttpClient httpClient = httpClientBuilder.build();

            RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
            requestConfigBuilder.setConnectTimeout(60 * 1000);
            requestConfigBuilder.setConnectionRequestTimeout(500);
            requestConfigBuilder.setSocketTimeout(60*1000);


            //该网页需要认证（用户名、密码）
            HttpClientContext context = new HttpClientContext();
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
            context.setCredentialsProvider(credentialsProvider);

            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(requestConfigBuilder.build());

            CloseableHttpResponse response = httpClient.execute(httpGet, context);

            InputStream inputStream = response.getEntity().getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }

            Document doc = DocumentHelper.parseText(sb.toString());
            Element rootElement = doc.getRootElement();
            Iterator iterator = rootElement.elementIterator();
            while (iterator.hasNext()) {
                Element next = (Element) iterator.next();
                Iterator iterator1 = next.elementIterator();
                RealHost realHost = new RealHost();
                while (iterator1.hasNext()) {
                    Element next1 = (Element) iterator1.next();
                    String name = next1.getName();
                    if ("busyGroupName".equals(name)) realHost.setBusyGroupName(next1.getStringValue());
                    if ("busyTitle".equals(name)) realHost.setBusyTitle(next1.getStringValue());
                    if ("healthTitle".equals(name)) realHost.setHealthTitle(next1.getStringValue());
                    if ("busyScoreStr".equals(name)) realHost.setBusyScoreStr(next1.getStringValue());
                    if ("healthScoreStr".equals(name)) realHost.setHealthScoreStr(next1.getStringValue());
                }
                realHostList.add(realHost);
            }
            response.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return realHostList;

    }

    @GetMapping("/getHealthData")
    public List<RealHost> getHealthData() {
        List<RealHost> realHostList = new ArrayList<RealHost>();
        long time = new Date().getTime();
        if (((time - start) / 1000) > 1800) {
            sessionId = loginTo();
        }
        realHostList = new ArrayList<>();
        String urlString = "http://"+healhost+"/cas/casrs/dashboard/health";//"http://10.230.126.249:8080/cas/casrs/hostpool/all";
        String cookie = "JSESSIONID=" + sessionId + "; path=/cas/; domain=10.230.126.249; HttpOnly; Expires=Tue, 19 Jan 2038 03:14:07 GMT;";
        URL url = null;
        try {
            url = new URL(urlString);
            URLConnection conn = url.openConnection();
            conn.setRequestProperty("Cookie", cookie);
            conn.setDoInput(true);
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            Document doc = DocumentHelper.parseText(sb.toString());
            Element rootElement = doc.getRootElement();
            Iterator iterator = rootElement.elementIterator();
            while (iterator.hasNext()) {
                Element next = (Element) iterator.next();
                Iterator iterator1 = next.elementIterator();
                RealHost realHost = new RealHost();
                while (iterator1.hasNext()) {
                    Element next1 = (Element) iterator1.next();
                    String name = next1.getName();
                    if ("hostName".equals(name)) realHost.setName(next1.getStringValue());
                    if ("cvkHealth".equals(name)) realHost.setCvkHealth(next1.getStringValue());
                }
                realHostList.add(realHost);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(realHostList.size());
        return realHostList;
    }

    /**
     * 5.3 查询共享文件系统详细信息
     *
     * @param id
     */
    @GetMapping("/cas/casrs/storage/shareFile")
    public void getHostsShareFileDec(@RequestParam("id") String id) {
        Map<String, Object> map = HttpUtil.doGet(hosts + "/cas/casrs/storage/shareFile/" + id);
        Map map1 = getHttpRtnBodyToMap(map);
        System.out.println(map1);
    }


    /**
     * 5.4 根据2 查询虚拟主机列表中的虚拟主机的id 查询虚拟主机详细信息
     */
    @GetMapping("/cas/casrs/vm")
    public void getVMHostsDec(@RequestParam("id") String id) {

        Map<String, Object> map = HttpUtil.doGet(hosts + "/cas/casrs/vm/" + id);
        Map map1 = getHttpRtnBodyToMap(map);
        System.out.println(map1);
    }

    @GetMapping("/deviceManager")
    public void deviceManager() {
        //{
        //"username": "admin",
        //"password": "Admin@123",
        //"scope": "0"
        //} 
        String signature = "";
        Map<String, String> para = new HashMap<>();
        para.put("username", "admin");
        para.put("password", "Admin@123");
        para.put("scope", "0");
        try {
            signature = SignatureUtils.generate("GET", para, AccessKeySecret);
            System.out.println(signature);
        } catch (Exception e) {
            e.printStackTrace();
        }
        long time = new Date().getTime();
        String url = OceanStor9000 + "/deviceManager/v1/rest/" + "OceanStor9000" + time + "/cluster_nas_service?signature=" + signature;
        System.out.println(url);
        Map<String, Object> map = HttpUtil.doGet(url);
        System.out.println(map);
        //实际可用容量=（总容量*只读水位-已用容量）*冗余配比利用率；
        //其中：总容量可在NAS管理界面查询到，为200.017TB
        //只读水位可在NAS管理界面查询到，为90%
        //已用容量可在NAS管理界面查询到，为59.474TB
        //冗余配比利用率为80%（+3:1的利用率）
    }



    /**
     * 没搞懂时间
     * @return
     */
    @GetMapping("/getToday")
    public Map<String,Object> getToday(){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR_OF_DAY,-8);
        String format = yyyyMMddHH.format(calendar.getTime())+"0000";
        /* 1. 调用方法的参数定义，并赋值 */
        String url = cimissUrl+"&interfaceId=getSevpWefcRffcByTimeAndStaID" /* 1.2 接口ID */
                + "&dataCode=SEVP_WEFC_RFFC" /* 1.3 必选参数（按需加可选参数） */ //资料：中国地面逐小时
                + "&elements=Station_Name,Province,City,Cnty,Town,Station_Id_C,Year,Mon,Day,Hour,TEM" //检索要素：站号、站名、小时降水、气压、相对湿度、能见度、2分钟平均风速、2分钟风向
                + "&time="+format //检索时间
                + "&staIds=57516"
                + "&orderby=Station_ID_C:ASC" //排序：按照站号从小到大
                + "&dataFormat=json" ; /* 1.4 序列化格式 */
        Map<String, Object> map = HttpUtil.doGet(url);
        Map<String,Object> httpRtnBodyToMap = getHttpRtnBodyToMap(map);
        List<Map<String,Object>> ds = (List<Map<String, Object>>) httpRtnBodyToMap.get("DS");
        for (Map<String, Object> map1 : ds) {
            if ("57516".equals(map1.get("Station_Id_C"))){
                return map1;
            }
        }

        return null;
    }

    public static Map getHttpRtnBodyToMap(Map<String, Object> map1) {
        byte[] bytes = (byte[]) map1.get("content");
        Map map = null;
        try {
            String res = new String(bytes, "UTF-8");
            return ConvertUtil.jsonStrToObject(res, Map.class);
        } catch (Exception e) {
            logger.error("解析http body出现错误", e);
            return null;
        }
    }

}

class RealProgress implements Runnable {
    private static Logger logger = Logger.getLogger(RealProgress.class);
    private int splitIndex,splitNum;
    private String cookie,monitorStr;
    private List<RealHost> realHostList;
    private List<RealHost> realHostCloudList;
    private CountDownLatch startGate, endGate;


    public RealProgress(String cookie,String monitorStr,int splitIndex, int splitNum, List<RealHost> realHostList,List<RealHost> realHostCloudList,CountDownLatch startGate, CountDownLatch endGate) {
        this.cookie = cookie;
        this.monitorStr = monitorStr;
        this.splitIndex = splitIndex; //xiabiao
        this.splitNum = splitNum;//geshu
        this.realHostList = realHostList;//
        this.realHostCloudList = realHostCloudList;
        this.startGate = startGate;
        this.endGate = endGate;
    }

    @Override
    public void run() {
            int i = splitIndex*splitNum;
            int len = i+splitNum;
            len = len > realHostList.size()? realHostList.size(): len;
            try {
                //所有线程等待
                startGate.await();
                URL url = null;
//                String monitorStr = null;
//                monitorStr = "http://10.230.126.249:8080/cas/casrs/host/id/%s/monitor";
//                monitorStr = "http://10.230.126.249:8080/cas/casrs/host/id/%s";
                for (; i < len; i++) {
                    RealHost realHost = realHostList.get(i);
                    String id = realHost.getId();
                    String monitorUrl = String.format(monitorStr, id);
                    url = new URL(monitorUrl);
                    URLConnection conn = url.openConnection();
                    conn.setRequestProperty("Cookie", cookie);
                    conn.setDoInput(true);
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                    Document doc = DocumentHelper.parseText(sb.toString());
                    Element rootElement = doc.getRootElement();
                    Iterator iterator = rootElement.elementIterator();
                    System.out.println("---111111 GG---");
                    RealHost couldRealHost = new RealHost();
                    couldRealHost.setId(realHost.getId());
                    couldRealHost.setName(realHost.getName());
                    while (iterator.hasNext()) {
                        Element next = (Element) iterator.next();
                        String name= next.getName();
                        if("cpuRate".equals(name)) couldRealHost.setCpuRate(next.getStringValue());
                        if("memRate".equals(name)) couldRealHost.setMemRate(next.getStringValue());
                        if("status".equals(name)) couldRealHost.setHostStatus(next.getStringValue());
                    }
                    realHostCloudList.add(couldRealHost);
                }
            } catch (Exception e) {
                logger.info(e.getMessage());
            } finally {
                endGate.countDown();
//                logger.info("st--"+i+"--//////"+this.splitIndex+"/////"+realHostList.get(i));
            }
    }
}

class VmProgress implements Runnable {
    private static Logger logger = Logger.getLogger(RealProgress.class);
    private int splitIndex,splitNum;
    private String cookie,monitorStr;
    private List<RealHost> realHostList;
    private List<VMHost> vmHostCloudList;//虚拟机列表
    private CountDownLatch startGate, endGate;


    public VmProgress(String cookie,String monitorStr,int splitIndex, int splitNum, List<RealHost> realHostList,List<VMHost> vmHostCloudList,CountDownLatch startGate, CountDownLatch endGate) {
        this.cookie = cookie;
        this.monitorStr = monitorStr;
        this.splitIndex = splitIndex; //xiabiao
        this.splitNum = splitNum;//geshu
        this.realHostList = realHostList;//
        this.vmHostCloudList = vmHostCloudList;
        this.startGate = startGate;
        this.endGate = endGate;
    }

    @Override
    public void run() {
        int i = splitIndex*splitNum;
        int len = i+splitNum;
        len = len > realHostList.size()? realHostList.size(): len;
        try {
            //所有线程等待
            startGate.await();
            URL url = null;
            for (; i < len; i++) {
                System.out.println("-------"+i+"//////"+this.splitIndex+"//////len////"+len+"----"+realHostList.get(i).getId()+"........"+realHostList.size());
                RealHost realHost = realHostList.get(i);
                String id = realHost.getId();
                String vmUrl = String.format(monitorStr, id);
                System.out.println("---111111 GG---");
                VMHost couldVmHost = new VMHost();
                couldVmHost.setId(realHost.getId());
                couldVmHost.setName(realHost.getName());
                double cpu = 0;
                double men = 0;
                try {
                    url = new URL(vmUrl);
                    URLConnection conn = url.openConnection();
                    conn.setRequestProperty("Cookie", cookie);
                    conn.setDoInput(true);
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = br.readLine()) != null) {
                        sb.append(line);
                    }
                    Document doc = DocumentHelper.parseText(sb.toString());
                    Element rootElement = doc.getRootElement();
                    Iterator iterator = rootElement.elementIterator();
                    while (iterator.hasNext()) {
                        Element next = (Element) iterator.next();
                        Iterator iterator1 = next.elementIterator();
                        while (iterator1.hasNext()) {
                            Element next1 = (Element) iterator1.next();
                            String name= next1.getName();
                            if("cpuRate".equals(name)) cpu = cpu + Double.parseDouble(next1.getStringValue());
                            if("memRate".equals(name)) men = men + Double.parseDouble(next1.getStringValue());
                            if("vmStatus".equals(name)) couldVmHost.setVmStatus(next1.getStringValue());//vm 状态
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                couldVmHost.setVmCupRate(cpu);
                couldVmHost.setVmMemRate(men);
                vmHostCloudList.add(couldVmHost);
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        } finally {
            endGate.countDown();
            logger.info("//////"+this.splitIndex+"/////"+realHostList.get(i));
        }
    }
}
